/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.corespring.restaurant.web.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.corespring.restaurant.model.Categoria;
import org.corespring.restaurant.model.Ingrediente;
import org.corespring.restaurant.model.Plato;
import org.corespring.restaurant.model.Receta;
import org.corespring.restaurant.model.RecetaId;
import org.corespring.restaurant.model.Tipo;
import org.corespring.restaurant.model.Usuario;
import org.corespring.restaurant.service.IngredienteManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.corespring.restaurant.service.PlatoManager;
import org.corespring.restaurant.service.RecetaManager;
import org.corespring.restaurant.service.ReporteManager;
import org.corespring.restaurant.service.UsuarioManager;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author aldo
 */
@Controller
public class RecetaController {

    RecetaManager recetaManager;
    PlatoManager platoManager;
    IngredienteManager ingredienteManager;
    UsuarioManager usuarioManager;
    ReporteManager reporteManager;

    @Autowired
    public RecetaController(RecetaManager oRecetaManager, PlatoManager oplatoManager, IngredienteManager oingredienteManager, UsuarioManager ousuarioManager, ReporteManager oreporteManager) {
        this.recetaManager = oRecetaManager;
        this.platoManager = oplatoManager;
        this.ingredienteManager = oingredienteManager;
        this.usuarioManager = ousuarioManager;
        this.reporteManager = oreporteManager;
    }

//    @RequestMapping("/adm_recetas.htm")
//    public void adm_recetas(Model model, @ModelAttribute("Receta") Receta receta) {
//        List<Receta> recetas = recetaManager.obtenerRecetas();
//        model.addAttribute("recetas", recetas);
//        model.addAttribute("receta", receta);
//    }
    @RequestMapping("/adm_recetas.htm")
    public void adm_recetas(Model model, @ModelAttribute("Plato") Plato plato) {
        List<Plato> platos = platoManager.obtenerListaPlatos();
        model.addAttribute("platos", platos);
        model.addAttribute("plato", plato);
    }

    @RequestMapping(value = "/adm_registroRecetaPlato.htm", method = RequestMethod.GET)
    public
    @ModelAttribute("plato")
    Plato obtenerRecetaPlato(
            @RequestParam(value = "idplato", required = false) String idPlato, HttpServletRequest request) {
        if (idPlato == null) {
            return new Plato();
        }
        if (!(idPlato.isEmpty() || idPlato.equals(""))) {
            Plato plato = platoManager.obtenerPlatoById(idPlato);
            if (plato == null) {
                return new Plato();
            }
            return plato;
        }
        return new Plato();
    }

    @ModelAttribute("categoria")
    public List<Categoria> listarCategorias() {

        List<Categoria> categorias = platoManager.obtenerCategorias();
        return categorias;
    }

    @ModelAttribute("tipo")
    public List<Tipo> listarTipos() {

        List<Tipo> tipos = platoManager.obtenerTipos();
        return tipos;
    }

    @RequestMapping("/adm_seleccionarIngrediente.htm")
    public void seleccionarIngrediente(
            @RequestParam(value = "idplato", required = false) String idPlato,
            Model model) {
        List<Receta> recetas = recetaManager.obtenerPlatoReceta(idPlato);
        String ids = "";
        int total = 0;
        for (Receta rec : recetas) {
            total += 1;
            if (total == 1) {
                ids = "'" + rec.getIngrediente().getIding().toString() + "'";
            } else {
                ids += ",'" + rec.getIngrediente().getIding().toString() + "'";
            }
        }
        List<Ingrediente> ingredientes = ingredienteManager.obtenerListaIngredientesNoSeleccionados(ids);
        model.addAttribute("ingredientes", ingredientes);
    }

    @RequestMapping(value = "/adm_listarReceta.htm", method = RequestMethod.GET)
    protected void ActualizarListaReceta(@RequestParam(value = "idplato", required = false) String idPlato, @RequestParam(value = "ids", required = false) String ids, @RequestParam(value = "cantidad", required = false) int cantidad,
            Model model, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        if (!ids.equals("")) {
            String[] array_ids = ids.split(";");
            for (int i = 0; i < array_ids.length; i++) {
                String id = array_ids[i];
                Date fecha = new Date();
                String hora = fecha.getHours() + ":" + fecha.getMinutes() + ":" + fecha.getSeconds();
                Plato oplato = platoManager.obtenerPlatoById(idPlato);
                Ingrediente oing = ingredienteManager.obtenerIngrediente(id);
                Usuario usu = usuarioManager.obtenerUsuarioById("admin");


                RecetaId ri = new RecetaId();
                ri.setIdplato(idPlato);
                ri.setIding(id);

                Receta r = new Receta();
                r.setId(ri);
                r.setPlato(oplato);
                r.setIngrediente(oing);
                r.setCantidad(cantidad);
                r.setFreg(fecha);
                r.setHreg(hora);
                r.setUsuario(usu);
                recetaManager.guardarReceta(r);
            }
        }


        List<Receta> recetas = recetaManager.obtenerListaIngredientesPorPlato(idPlato);
        StringBuilder providerList = new StringBuilder();
        providerList.append("").append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"gwlines arborder\">").append("<tr>").append("<th width=\"250\" class=\"rborder\">Ingrediente</th>").append("<th width=\"100\" class=\"rborder\">Costo</th>").append("<th width=\"150\" class=\"rborder\">Cantidad</th>").append("<th width=\"150\" class=\"rborder\">Unidad</th>").append("<th width=\"100\" class=\"rborder\">Opciones</th>").append("</tr>");
        for (Receta r : recetas) {
            Ingrediente oIng = ingredienteManager.obtenerIngrediente(r.getIngrediente().getIding());
            providerList.append("<tr>").append("<td class=\"rborder\">").append(oIng.getDesing()).append("</td>").append("<td class=\"rborder\">").append(oIng.getCosto()).append("</td>").append("<td class=\"rborder\">").append(r.getCantidad()).append("</td>").append("<td class=\"rborder\">").append(oIng.getUnidad().getUnicod()).append("</td>").append("<td style=\"text-align:center\"><a href=\"javascript:eliminarReceta('" + idPlato + "','" + oIng.getIding().toString() + "')\"><img src=\"images/imagesAdm/icon_X.png\" alt=\"picture\" width=\"13\" height=\"14\" class=\"tabpimpa\" /></a>").append("</td>").append("</tr>");
        }
        providerList.append("</table>");
        //response.setContentType( "text/plain; charset=UTF-8" );
        response.getOutputStream().write(providerList.toString().getBytes());
    }

    @RequestMapping("/eliminarReceta.htm")
    protected void eliminarReceta(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "idplato", required = false) String idplato, @RequestParam(value = "iding", required = false) String iding)
            throws Exception {
        recetaManager.EliminarReceta(idplato, iding);
        List<Receta> recetas = recetaManager.obtenerListaIngredientesPorPlato(idplato);
        StringBuilder providerList = new StringBuilder();
        providerList.append("").append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"gwlines arborder\">").append("<tr>").append("<th width=\"250\" class=\"rborder\">Ingrediente</th>").append("<th width=\"100\" class=\"rborder\">Costo</th>").append("<th width=\"150\" class=\"rborder\">Cantidad</th>").append("<th width=\"150\" class=\"rborder\">Unidad</th>").append("<th width=\"100\" class=\"rborder\">Opciones</th>").append("</tr>");
        for (Receta r : recetas) {
            Ingrediente oIng = ingredienteManager.obtenerIngrediente(r.getIngrediente().getIding());
            providerList.append("<tr>").append("<td class=\"rborder\">").append(oIng.getDesing()).append("</td>").append("<td class=\"rborder\">").append(oIng.getCosto()).append("</td>").append("<td class=\"rborder\">").append(r.getCantidad()).append("</td>").append("<td class=\"rborder\">").append(oIng.getUnidad().getUnicod()).append("</td>").append("<td style=\"text-align:center\"><a href=\"javascript:eliminarReceta('" + idplato + "','" + oIng.getIding().toString() + "')\"><img src=\"images/imagesAdm/icon_X.png\" alt=\"picture\" width=\"13\" height=\"14\" class=\"tabpimpa\" /></a>").append("</td>").append("</tr>");
        }
        providerList.append("</table>");
        response.getOutputStream().write(providerList.toString().getBytes());
    }

    @RequestMapping("/exportarListaRecetaReporte.htm")
    public void exportarListaRecetaReporte(HttpServletResponse response) throws Exception {
        OutputStream out = response.getOutputStream();
        HSSFWorkbook dataWorkbook = null;

        try {
            dataWorkbook = reporteManager.obtenerListaRecetaReporte();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + "RecetaReporte.xls" + "\"");

        } catch (Exception e) {
            System.out.println("El siguiente error ocurrio: " + e.getMessage());
        } finally {
            dataWorkbook.write(out);
            out.close();
        }
    }

//    @RequestMapping(value = "/platosdet.htm", method = RequestMethod.GET)
//    public void platodet(@RequestParam(value = "idplato", required = false) String idPlato,
//            Model model,
//            @ModelAttribute("Plato") Plato plato)
//    {
//            ,@ModelAttribute("Ingrediente") Ingrediente ingrediente) {
//
//        plato = platoManager.obtenerPlatoById(idPlato);
//
//        List<Receta> recetas = recetaManager.obtenerListaIngredientesPorPlato(idPlato);
//        List<Ingrediente> ingredientes = new ArrayList<Ingrediente>();
//        for (Receta r : recetas) {
//            Ingrediente oIng = ingredienteManager.obtenerIngrediente(r.getIngrediente().getIding());
//            ingredientes.add(oIng);
//        }
//        model.addAttribute("plato", plato);
//        model.addAttribute("ingredientes", ingredientes);
//        model.addAttribute("ingrediente", ingrediente);
//    }
    

}
